package org.anyline.simple.transaction;

import org.anyline.data.transaction.TransactionState;
import org.anyline.entity.DataRow;
import org.anyline.entity.DataSet;
import org.anyline.proxy.ServiceProxy;
import org.anyline.proxy.TransactionProxy;
import org.anyline.service.AnylineService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class TransactionTest {

    @Test
    public void test() throws Exception{
        AnylineService service = ServiceProxy.service("crm");
        service.truncate("crm_user");
        DataSet set = new DataSet();
        for(int i=0; i<10; i++){
            DataRow row = set.add();
            row.put("CODE", i);
        }
        service.insert("crm_user", set);
        long qty = service.count("crm_user");
        System.out.println("插入10行后 当前行数:"+qty);

        //启动事务
        TransactionState state = TransactionProxy.start("crm");
        //或service.start();//因为service绑定了数据源 所以不需要数据源名称这个参数
        DataRow row = new DataRow();
        row.put("CODE", 11);
        service.insert("crm_user",row);
        qty = service.count("crm_user");
        System.out.println("插入第11行 未提交事务 当前行数:"+qty);
        TransactionProxy.commit(state);
        qty = service.count("crm_user");
        System.out.println("插入第11行 已提交事务 当前行数:"+qty);


        state = TransactionProxy.start("crm");
        row = new DataRow();
        row.put("CODE", 11);
        service.insert("crm_user",row);
        qty = service.count("crm_user");
        System.out.println("插入第12行 未回滚事务 当前行数:"+qty);
        TransactionProxy.rollback(state);
        qty = service.count("crm_user");
        System.out.println("插入第12行 已回滚事务 当前行数:"+qty);
    }

    @Test
    public void test2() throws Exception{
        AnylineService service = ServiceProxy.service();
        service.truncate("crm_user");
        DataSet set = new DataSet();
        for(int i=0; i<10; i++){
            DataRow row = set.add();
            row.put("CODE", i);
        }
        service.insert("crm_user", set);
        long qty = service.count("crm_user");
        System.out.println("插入10行后 当前行数:"+qty);

        //启动事务
        TransactionState state = TransactionProxy.start();
        DataRow row = new DataRow();
        row.put("CODE", 11);
        service.insert("crm_user",row);
        qty = service.count("crm_user");
        System.out.println("插入第11行 未提交事务 当前行数:"+qty);
        TransactionProxy.commit(state);
        qty = service.count("crm_user");
        System.out.println("插入第11行 已提交事务 当前行数:"+qty);


        state = TransactionProxy.start();
        row = new DataRow();
        row.put("CODE", 11);
        service.insert("crm_user",row);
        qty = service.count("crm_user");
        System.out.println("插入第12行 未回滚事务 当前行数:"+qty);
        TransactionProxy.rollback(state);
        qty = service.count("crm_user");
        System.out.println("插入第12行 已回滚事务 当前行数:"+qty);
    }
}
